import { Message } from 'element-ui'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { getUserInfo, login } from '@/api/user'
import router from '@/router'
import store from '@/store'
const state = {
  token: getToken(),
  userInfo: {}
}

const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  login({ commit, dispatch }, data) {
    login(data).then(res => {
      commit('setToken', res)
      // 提示登录成功
      Message.success('登录成功')
      // 跳转首页
      router.push('/dashboard')
    }).catch(error => {
      // 提示登录失败
      console.log(error)
    })
  },
  getUserInfo({ commit }) {
    // 获取用户信息
    getUserInfo().then(res => {
      // 设置用户信息
      commit('setUserInfo', res)
    }).catch(error => {
      // 提示获取用户信息失败
      console.dir(error)
      if (error.message === '获取资料失败') {
        // 登录失效
        store.dispatch('user/logout')
        // //跳转登录页
        router.push('/login')
      }
    })
  },
  logout({ commit }) {
    // 清空token
    commit('removeToken')
    // 清空用户信息
    commit('removeUserInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

